package com.yjf.ljr.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.yjf.ljr.activity.IjActivity;

@SuppressWarnings("rawtypes")
public class CommonAdapter extends BaseAdapter {

	private Context mContext;
	private List mData = null;
	private int mLayoutId;
	private Class mClazz;
	private LayoutInflater mInflater;
	private HandleCallBack mHandler = null;

	/**
	 * 初始化通用 Adapter
	 * 
	 * @param context
	 *            上下文
	 * @param data
	 *            自定义类型的数据列表
	 * @param layoutId
	 *            布局文件的 ID
	 * @param clazz
	 *            布局文件对应的ViewHolder
	 * @param handle
	 *            回调函数处理每一项数据
	 */
	public CommonAdapter(Context context, List data, int layoutId, Class clazz, HandleCallBack handle) {
		this.mContext = context;
		this.mData = data;
		this.mLayoutId = layoutId;
		this.mClazz = clazz;
		this.mHandler = handle;
		this.mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return mData.size();
	}

	@Override
	public Object getItem(int position) {
		return mData.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public List getList() {
		return mData;
	}

	public void removeItem(int position) {
		mData.remove(position);
		notifyDataSetChanged();
	}

	public void removeItemAll() {
		mData.clear();
		notifyDataSetChanged();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Object holder = null;
		if (null == convertView) {
			convertView = mInflater.inflate(mLayoutId, null);

			/**
			 * 这里要调用IjActivity的静态initComponents，另外ViewHolder所在类还得继承自IjActivity
			 * 否则都会导致field.getAnnotation(ID.class);找不到
			 */
			try {
				holder = mClazz.newInstance();
			} catch (Exception e) {
				e.printStackTrace();
			}
			IjActivity.initComponents(mContext, convertView, holder);
			convertView.setTag(holder);
		} else {
			holder = convertView.getTag();
		}

		mHandler.handle(position, convertView, parent, holder, mData.get(position));
		return convertView;
	}

	// 回调接口
	public interface HandleCallBack {
		/**
		 * 处理每一个item
		 * 
		 * @param position
		 *            位置
		 * @param convertView
		 *            视图项
		 * @param parent
		 *            父窗口
		 * @param holder
		 *            ViewHolder
		 * @param item
		 *            回调对应position的数据项
		 */
		public void handle(int position, View convertView, ViewGroup parent, Object holder, Object item);
	}
}
